package com.liang.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JdbcController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @GetMapping("/userList")
    //查询数据库的所有信息
    public List<Map<String,Object>> userList(){
        String sql = "select * from mybatis.user1";
        List<Map<String, Object>> userList = jdbcTemplate.queryForList(sql);
        return userList;
    }

    @RequestMapping("/addUser")
    //添加
    public String addUser(){
        String sql = "insert into mybatis.user1(id,name,pwd) values(4,'苏打绿','123456')";
        jdbcTemplate.update(sql);
        return "update-ok";
    }

    @RequestMapping("/updateUser/{id}")
    //添加
    public String updateUser(@PathVariable("id") int id){
        String sql = "update mybatis.user1 set name=?,pwd=? where id="+id;
        Object[] object = new Object[2];
        object[0] = "苏打绿2";
        object[1] = "1234";
        jdbcTemplate.update(sql,object);
        return "update-ok2";
    }

    @RequestMapping("/deleteUser/{id}")
    //添加
    public String deleteUser(@PathVariable("id") int id){
        String sql = "delete from mybatis.user1 where id=?";
        jdbcTemplate.update(sql,id);
        return "delete-ok";
    }
}
